package com.gz.spring.tx.service;

import com.gz.spring.tx.dao.GoodsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service //将GoodsService注入到spring容器
public class GoodsService {

    @Resource
    private GoodsDao goodsDao;

    public void buyGoods(int userId, int goodsId,int amount) {
        //得到商品价格
        Float price = goodsDao.queryPriceById(goodsId);
        //减少用户余额
        goodsDao.updateBalance(userId, price*amount);
        //减少库存量
        goodsDao.updateAmount(goodsId, amount);
    }

    //1.propagation = Propagation.REQUIRED表示一个大事务内的小事务出现回滚(即出错),整个事务都回滚
    //propagation = Propagation.REQUIRED是默认值，不写就默认是这个
    //2.propagation = Propagation.REQUIRES_NEW 表示每个都是单独的事务，
    // 其中一个出错自行回滚，但不影响其他的事务，即只有出错的回滚，其他不回滚
    //3.Propagation.REQUIRED和Propagation.REQUIRES_NEW只出现一种，
    // 即要不全是Propagation.REQUIRES_NEW，要不全是Propagation.REQUIRED
    @Transactional(propagation = Propagation.REQUIRES_NEW) //声明式事务处理
    public void buyGoodsByTx(int userId, int goodsId,int amount) {
        //得到商品价格
        Float price = goodsDao.queryPriceById(goodsId);
        //减少用户余额
        goodsDao.updateBalance(userId, price*amount);
        //减少库存量
        goodsDao.updateAmount(goodsId, amount);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW) //声明式事务处理
    public void buyGoodsByTx2(int userId, int goodsId,int amount) {
        //得到商品价格
        Float price = goodsDao.queryPriceById2(goodsId);
        //减少用户余额
        goodsDao.updateBalance2(userId, price*amount);
        //减少库存量
        goodsDao.updateAmount2(goodsId, amount);
    }
}
